import axios from "axios";
import Qs from "qs";
import {
	Message,
	Loading
} from "element-ui";
import router from "../router/index";
import common from "../utils/common"
import {
	saveAs
} from 'file-saver'
import moment from "moment"
let loading;

function startLoading() {
	//使用Element loading-start 方法
	loading = Loading.service({
		target: document.querySelector(".custom-loading"),
		lock: true,
		background: "rgba(0, 0, 0, 0.8)",
		text: '拼命加载中',
		spinner: 'el-icon-loading'
	});
}

function endLoading() {
	//使用Element loading-close 方法
	loading.close();
}

let needLoadingRequestCount = 0;
export function showFullScreenLoading() {
	if (needLoadingRequestCount === 0) {
		startLoading();
	}
	needLoadingRequestCount++;
}

export function tryHideFullScreenLoading() {
	if (needLoadingRequestCount <= 0) return;
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		endLoading();
	}
}

axios.defaults.headers['client'] = 'admin'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
//超时时间10秒
axios.defaults.timeout = 10000;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true


axios.defaults.baseURL = "/server"

const upFileUrl = "/server/api/app/file/up"
const uploadHeaders = () => {
	return {
		client: 'admin',
		authorization: getToken(),
	}
}
/**
 * 获取token
 */
function getToken() {
	let token = localStorage.getItem("token")
	if (token) {
		return "Bearer_" + token
	} else {
		return "";
	}
}

// http request 拦截器
axios.interceptors.request.use(
	config => {
		console.info("request拦截器", config)
		config.headers['authorization'] = getToken();
		showFullScreenLoading();
		return config;
	},
	error => {
		common.msgError(error.message)
		return Promise.reject(error);
	}
);

//http response拦截器
axios.interceptors.response.use(
	response => {
		// 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
		// 否则的话抛出错误
		console.info("response拦截器", response)
		let config = response.config
		if (response.config.responseType == 'blob') {
			tryHideFullScreenLoading();
			let blob = new Blob([response.data]);
			let fileName = JSON.parse(config.data).fileName
			if(fileName){
				fileName = `${getNoType(fileName)}_${moment().format('YYYYMMDDHHmmss')}.`+getType(fileName)
			}else{
				fileName = moment().format('YYYYMMDDHHmmss')
			}
			
			saveAs(blob, decodeURI(fileName))
			return Promise.resolve(response);
		}
		if (response.status === 200) {
			tryHideFullScreenLoading();
			let result = response.data
			let code = result.code
			if (code == 200) {
				if (config.method == 'post' || config.method == 'put' || config.method == 'delete') {
					common.msgSuccess("操作成功")
				}
				return Promise.resolve(result.result);
			} else {
				let isErrorToast = true
				if (config.hasOwnProperty('isErrorToast')) {
					isErrorToast = config.isErrorToast
				}
				if (code == 401) {
					if (router.currentRoute.path != '/login') {
						//清除storage中数据
						localStorage.clear();
						sessionStorage.clear();
						//跳转登录页
						router.replace("/login");
					}
					if (isErrorToast) {
						common.msgWarn(result.message)
					}
				} else if (result.code == 500) {
					//系统错误
					if (isErrorToast) {
						common.msgError(result.message)
					}
				} else if (result.code == 301) {
					//警告
					if (isErrorToast) {
						common.msgWarn(result.message);
					}
				} else if (result.code == 2004) {
					//没有权限
					if (isErrorToast) {
						common.msgWarn(result.message);
					}
				} else if (result.code == 2002) {
					//数据校验错误
					if (isErrorToast) {
						common.msgWarn(result.message);
					}
				} else if (result.code == 2001) {
					//填写值不符合要求
					if (isErrorToast) {
						common.msgWarn(result.message);
					}
				}
				return Promise.reject(result.message);
			}
		} else {
			return Promise.reject(response);
		}
	},
	error => {
		console.info("response", error)
		tryHideFullScreenLoading();
		common.msgError(error.message)
		return Promise.reject(error);
	}
);
function getType(fileName) {
	let index = fileName.lastIndexOf(".");
	let ext = fileName.substr(index + 1);
	return ext.toLowerCase();
}
function getNoType(fileName) {
	let index = fileName.lastIndexOf(".");
	let ext = fileName.substr(0,index);
	return ext.toLowerCase();
}
export default {
	name: "http",

	upFileUrl: upFileUrl,
	getToken: getToken,
	uploadHeaders: uploadHeaders,
	//get请求
	get(url, params, config) {
		config = config ? config : {}
		return axios.get(url, {
			params: params
		}, config)
	},
	//post请求
	post(url, params, config) {
		config = config ? config : {}
		return axios.post(url, params, config);
	},
	//put请求
	put(url, params, config) {
		config = config ? config : {}
		return axios.put(url, params, config)
	},
	//put请求
	delete(url, params, config) {
		config = config ? config : {}
		return axios.delete(url, {
			params: params
		}, config)
	},
	//下载
	download(url, params,config) {
		config = config ? config : {},
		config.responseType = 'blob'
		return axios.post(url, params, config)
	},
	// 上传
	upload(url, params,config) {
		const formData = new FormData()
		for (let key in params) {
			formData.append(key, params[key])
		}
		config = config ? config : {},
		config['Content-Type'] = 'multipart/form-data'
		return axios.post(url, formData,config)
	}
};